Screenshot%201446-01-18%20at%2012.05.20%E2%80%AFAM.png

Numpy¶

Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.

In [ ]:
# install numpy 
In [1]:
pip install numpy
Requirement already satisfied: numpy in c:\users\dell\anaconda3\lib\site-packages (1.26.4)
Note: you may need to restart the kernel to use updated packages.

To use Numpy, we first need to import the numpy package. By convention, we


import it using the alias np. Then, when we want to use modules or functions in this library, we preface them with np.

In [4]:
import numpy as np

We can create a numpy array by passing a Python list to np.array().

In [7]:
a = np.array([1, 2, 3])  # Create a rank 1 array
In [9]:
print(type(a), a.shape, a[0], a[1], a[2])
a[0] = 5                 # Change an element of the array
print(a)  
<class 'numpy.ndarray'> (3,) 1 2 3
[5 2 3]
In [11]:
b = np.array([[1,2,3],[3,4,3]])   # Create a rank 2 array
print(b)
[[1 2 3]
 [3 4 3]]
In [13]:
print(b[1][1])
4
In [15]:
print(b.shape)
(2, 3)

There are often cases when we want numpy to initialize the values of the


array for us. numpy provides methods like ones(), zeros(), and random.random() for these cases. We just pass them the number of elements we want it to generate:

In [18]:
a = np.zeros((2,2))  # Create an array of all zeros
print(a)
[[0. 0.]
 [0. 0.]]
In [20]:
b = np.ones((1,2))   # Create an array of all ones
print(b)
[[1. 1.]]
In [22]:
c = np.full((2,3), 9) # Create a constant array
print(c)
[[9 9 9]
 [9 9 9]]
In [24]:
e = np.random.random((2,2)) # Create an array filled with random values
print(e)
[[0.48000656 0.21906727]
 [0.99940097 0.76741752]]

Matplotlib¶

Matplotlib is a plotting library. In this section we give a brief introduction to the matplotlib.pyplot module, which provides a plotting system similar to that of MATLAB.

By convention, we typically import this module using the plt alias:

In [ ]:
# install matplotlib 
In [26]:
pip install matplotlib
Requirement already satisfied: matplotlib in c:\users\dell\anaconda3\lib\site-packages (3.8.4)
Requirement already satisfied: contourpy>=1.0.1 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (1.2.0)
Requirement already satisfied: cycler>=0.10 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (4.51.0)
Requirement already satisfied: kiwisolver>=1.3.1 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (1.4.4)
Requirement already satisfied: numpy>=1.21 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (1.26.4)
Requirement already satisfied: packaging>=20.0 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (23.2)
Requirement already satisfied: pillow>=8 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (10.3.0)
Requirement already satisfied: pyparsing>=2.3.1 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (3.0.9)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\dell\anaconda3\lib\site-packages (from matplotlib) (2.9.0.post0)
Requirement already satisfied: six>=1.5 in c:\users\dell\anaconda3\lib\site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
In [28]:
import matplotlib.pyplot as plt
In [30]:
print(3 * np.pi)
9.42477796076938
In [32]:
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
# Plot the points using matplotlib
plt.plot(x, y)

# Show the figure.
plt.show()
No description has been provided for this image
In [34]:
print(x)
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.  3.1 3.2 3.3 3.4 3.5
 3.6 3.7 3.8 3.9 4.  4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5.  5.1 5.2 5.3
 5.4 5.5 5.6 5.7 5.8 5.9 6.  6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7.  7.1
 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 8.  8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9
 9.  9.1 9.2 9.3 9.4]
In [36]:
y_sin = np.sin(x)
y_cos = np.cos(x)
# Plot the points using matplotlib
plt.plot(x, y_sin, label='Sine')
plt.plot(x, y_cos, label='Cosine')

plt.legend() # uses the label arguments given above

plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')

# Show the figure.
plt.show()
No description has been provided for this image

pandas¶

In [ ]:
# install pandas 
In [39]:
pip install pandas
Requirement already satisfied: pandas in c:\users\dell\anaconda3\lib\site-packages (2.2.2)
Requirement already satisfied: numpy>=1.26.0 in c:\users\dell\anaconda3\lib\site-packages (from pandas) (1.26.4)
Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\dell\anaconda3\lib\site-packages (from pandas) (2.9.0.post0)
Requirement already satisfied: pytz>=2020.1 in c:\users\dell\anaconda3\lib\site-packages (from pandas) (2024.1)
Requirement already satisfied: tzdata>=2022.7 in c:\users\dell\anaconda3\lib\site-packages (from pandas) (2023.3)
Requirement already satisfied: six>=1.5 in c:\users\dell\anaconda3\lib\site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
In [41]:
# Import the pandas library
import pandas as pd

# Create a sample DataFrame with names
data = {
    'First Name': ['John', 'Sarah', 'Michael', 'Emily', 'David'],
    'Last Name': ['Doe', 'Smith', 'Johnson', 'Wilson', 'Lee'],
    "age":[21,22,23,24,25]
}
df = pd.DataFrame(data)

# Display the DataFrame
print(df)
  First Name Last Name  age
0       John       Doe   21
1      Sarah     Smith   22
2    Michael   Johnson   23
3      Emily    Wilson   24
4      David       Lee   25
In [43]:
df['Full Name'] = df['First Name'] + ' ' + df['Last Name']
print(df)
  First Name Last Name  age        Full Name
0       John       Doe   21         John Doe
1      Sarah     Smith   22      Sarah Smith
2    Michael   Johnson   23  Michael Johnson
3      Emily    Wilson   24     Emily Wilson
4      David       Lee   25        David Lee
In [45]:
pip install openpyxl
Requirement already satisfied: openpyxl in c:\users\dell\anaconda3\lib\site-packages (3.1.2)
Requirement already satisfied: et-xmlfile in c:\users\dell\anaconda3\lib\site-packages (from openpyxl) (1.1.0)
Note: you may need to restart the kernel to use updated packages.
In [47]:
# Save the DataFrame to an Excel file
df.to_excel('names_data2.xlsx', index=False)

object detection¶

Screenshot 1446-01-18 at 1.11.55 AM.png

Screenshot 1446-01-18 at 1.12.57 AM.png

Face mask detection¶

In [ ]:
#Cvlib is A simple, high level, easy-to-use open source Computer Vision library for Python.

#Face detection Detecting faces in an image is as simple as just calling the function detect_face().

#Object detection Detecting common objects in the scene is enabled through a single function call detect_common_objects().
In [ ]:
pip install cvlib
In [ ]:
pip install opencv-python
In [ ]:
pip install tensorflow
In [15]:
import cv2
import cvlib as cv
from cvlib.object_detection import draw_bbox
from PIL import Image
from IPython import display
import numpy as np
In [17]:
# Read the image into a numpy array
filename="C:\\Users\\dell\\OneDrive\\Desktop\\hh.jpg"
img = cv2.imread(filename)
img
Out[17]:
array([[[ 28,  49,  70],
        [ 27,  48,  69],
        [ 26,  50,  70],
        ...,
        [153, 159, 158],
        [153, 159, 158],
        [153, 158, 157]],

       [[ 28,  49,  70],
        [ 28,  49,  70],
        [ 26,  50,  70],
        ...,
        [151, 156, 157],
        [151, 156, 157],
        [151, 156, 157]],

       [[ 27,  51,  71],
        [ 26,  50,  70],
        [ 27,  50,  72],
        ...,
        [150, 157, 160],
        [153, 158, 161],
        [154, 159, 162]],

       ...,

       [[ 20,  20,  20],
        [ 15,  15,  15],
        [ 14,  14,  14],
        ...,
        [ 70, 103, 159],
        [ 60,  94, 153],
        [ 66,  96, 153]],

       [[ 19,  21,  21],
        [ 14,  16,  16],
        [ 13,  15,  15],
        ...,
        [ 71, 102, 153],
        [ 62,  95, 151],
        [ 66,  96, 151]],

       [[ 21,  23,  23],
        [ 14,  16,  16],
        [ 13,  15,  15],
        ...,
        [ 69,  99, 146],
        [ 65,  96, 149],
        [ 67,  95, 149]]], dtype=uint8)
In [19]:
im = Image.open(filename)
im.show()
In [21]:
print("OpenCV version:", cv2.__version__)
OpenCV version: 4.10.0
In [29]:
bbox, label, conf = cv.detect_common_objects(img)

# Print detected objects with confidence level
for b, l, c in zip(bbox,label, conf):
    print(f"Detected object: {l} with confidence level of {c}, bbox: {b}\n")

# Create a new image that includes the bounding boxes
output_image = draw_bbox(img, bbox, label, conf)
     
# Save the image in the directory images_with_boxes
cv2.imwrite(f'images_with_box.jpg', output_image)
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
Cell In[29], line 1
----> 1 bbox, label, conf = cv.detect_common_objects(img)
      3 # Print detected objects with confidence level
      4 for b, l, c in zip(bbox,label, conf):

File ~\anaconda3\Lib\site-packages\cvlib\object_detection.py:125, in detect_common_objects(image, confidence, nms_thresh, model, enable_gpu)
    123 if initialize:
    124     classes = populate_class_labels()
--> 125     net = cv2.dnn.readNet(weights_file_abs_path, config_file_abs_path)
    126     initialize = False
    128 # enables opencv dnn module to use CUDA on Nvidia card instead of cpu

error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\darknet\darknet_io.cpp:705: error: (-215:Assertion failed) separator_index < line.size() in function 'cv::dnn::darknet::ReadDarknetFromCfgStream'
In [ ]:
im = Image.open("images_with_box.jpg")
im.show()
In [27]:
 
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
Cell In[27], line 8
      5 weights_file = 'path/to/your/weights.weights'
      7 # Load the network architecture and weights
----> 8 net = cv2.dnn.readNetFromDarknet(config_file, weights_file)
     10 # Optionally set preferable backend and target to improve performance
     11 net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)

error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\darknet\darknet_importer.cpp:210: error: (-212:Parsing error) Failed to open NetParameter file: path/to/your/config.cfg in function 'cv::dnn::dnn4_v20240521::readNetFromDarknet'
In [ ]: